﻿using System.Web.Mvc;
using System.Web.Hosting;
using Web7.Extensions;

namespace Web7.Mvc.ViewEngines
{
    public class Web7WebFormViewEngine : WebFormViewEngine, IWeb7ViewEngine
    {
        private string _rootPath;
        private readonly VirtualPathProvider _virtualPathProvider;

        public Web7WebFormViewEngine(VirtualPathProvider virtualPathProvider)
        {
            _virtualPathProvider = virtualPathProvider;
        }

        #region IWeb7ViewEngine Members

        public void SetRootPath(string rootPath, bool onlySearchRootPathForPartialViews)
        {
            rootPath = rootPath.EnsureVirtualDirectory();
            MasterLocationFormats = new[]
            {
                rootPath + "/Views/{1}/{0}.master",
                rootPath + "/Views/Shared/{0}.master"
            };

            ViewLocationFormats = new[]
            {
                rootPath + "/Views/{1}/{0}.aspx",
                rootPath + "/Views/Shared/{0}.aspx"
                //rootPath + "/Views/{1}/{0}.ascx",
                //rootPath + "/Views/Shared/{0}.ascx"
            };
            PartialViewLocationFormats = !onlySearchRootPathForPartialViews
                ? ViewLocationFormats
                : new[] { rootPath + "/{0}.ascx" };

            AreaMasterLocationFormats = new[]
            {
                rootPath + "/Area/{2}/Views/{1}/{0}.master",
                rootPath + "/Area/{2}/Views/Shared/{0}.master"
            };
            AreaViewLocationFormats = new[]
            {
                rootPath + "/Area/{2}/Views/{1}/{0}.aspx",
                rootPath + "/Area/{2}/Views/Shared/{0}.aspx"
                //rootPath + "/Area/{2}/Views/{1}/{0}.ascx",
                //rootPath + "/Area/{2}/Views/Shared/{0}.ascx"
            };
            AreaPartialViewLocationFormats = !onlySearchRootPathForPartialViews
                ? AreaViewLocationFormats
                : new[] { rootPath + "/Area/{2}/{0}.ascx" };

            _rootPath = rootPath;
        }

        public string RootPath
        {
            set { SetRootPath(value, false); }
            get { return _rootPath; }
        }
        
        public virtual FileEngineResult FindFile(string fileName)
        {
            if (!fileName.StartsWith("/"))
            {
                fileName = "/" + fileName;
            }

            fileName = _rootPath + fileName;

            if (_virtualPathProvider.FileExists(fileName))
            {
                return new FileEngineResult(fileName, this);
            }

            return new FileEngineResult(new[] { fileName });
        }

        #endregion

    }
}
